package panda.query.condition;

import panda.query.scan.Scanner;
import panda.query.struct.Attribute;
import panda.query.struct.Constant;
import panda.query.struct.NullConstant;
import panda.query.tree.QueryTreeNode;
import panda.server.Panda;
import panda.syntax.SelectStm;
import panda.transaction.Transaction;

public class ExistsExpression implements BooleanExpression {
	
	private QueryTreeNode tn = null;
	public boolean neg;
	
	SelectStm stm;
	
	public ExistsExpression(boolean neg, SelectStm subquery) {
		this.neg = neg;
		this.stm = subquery;
	}

	@Override
	public int equateWithConstant(Attribute attr) {
		return 0;
	}

	@Override
	public int isSatisfied(Scanner s, Transaction tx) {
		if (tn == null) tn = Panda.getPlanner().executeSubQuery(stm, tx);
		
		for (AttributeName a : stm.subReferring)
			a.stubValue(s.getValue(a.getAttribute()));
		
		Scanner sc = tn.open();
		
		while (sc.next()) {
			sc.close();
			return 1;
		}
		
		sc.close();
		return 0;
	}

	@Override
	public double reductionFactor(QueryTreeNode n) {
		return 1;
	}

}
